//
//  PPPasswordSettingViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/27/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPPasswordSettingViewController.h"

#import "PPNetworkService.h"
#import "PPRetrieveViewController.h"
#define kSettingFont ([UIFont boldSystemFontOfSize:16])
@interface PPPasswordSettingViewController ()
@property (strong, nonatomic) IBOutlet UITextField *currentPasswordField;
@property (strong, nonatomic) IBOutlet UITextField *nextPasswordField;
@property (strong, nonatomic) IBOutlet UIButton *hiddenButton;
@property (weak, nonatomic) IBOutlet UIView *topLine;
@property (weak, nonatomic) IBOutlet UIView *centerLine;
@property (weak, nonatomic) IBOutlet UIView *bottomLine;
@end

@implementation PPPasswordSettingViewController


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.view.backgroundColor = WHITE;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"设置" image:@"nav_back" target:self action:@selector(popViewPreviousController)];
    self.tableView.bounces = NO;
//    [_topLine addTopBorderWithColor:kLineColor andWidth:kLineWidth];
    [_centerLine addBottomBorderWithColor:kLineColor andWidth:kLineWidth];
    [_bottomLine addBottomBorderWithColor:kLineColor andWidth:kLineWidth];

    __weak typeof(self) weakSelf = self;
    [self setNavigationRightTitle:@"保存" titleColor:[UIColor colorWithRGBHex:0xffdd17] action:^{
        [weakSelf saveItemDidPressed];
    }];
    
    if (IS_IOS_8) {
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PFFontMedium(16)} forState:UIControlStateNormal];
    }else{
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 16)} forState:UIControlStateNormal];
    }
    
    
    self.navigationItem.rightBarButtonItem.tintColor = COLORA(0, 118, 255);
    
    
    _hiddenButton.adjustsImageWhenHighlighted = NO;
    [_hiddenButton setImage:[UIImage imageNamed:@"code-off"] forState:UIControlStateNormal];
    [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateHighlighted|UIControlStateSelected];
    [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateSelected];
    [_hiddenButton addTarget:self action:@selector(hiddenButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];

    [self textFieldDidChanged];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChanged) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)hiddenButtonDidPressed:(UIButton *)button {
    button.selected = !button.selected;

    _nextPasswordField.secureTextEntry = !button.selected;
}

- (void)saveItemDidPressed {

    [_currentPasswordField resignFirstResponder];
    [_nextPasswordField resignFirstResponder];
    
    NSString *old = _currentPasswordField.text;
    NSString *new = _nextPasswordField.text;

    if ([old length] < 6 || [old length] > 16)
    {
        [self.view toastMessage:@"密码长度要求在6-16位" duration:1.f];
        return;
    }
    //去除空格符
    new = [new stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //匹配正则表达式规则
    NSString *regex = @"^[\\w\\-\\_\u4e00-\u9fa5]{6,16}$";
    //    @"(^[\u4e00-\u9fa5]+$)"  @"^[\\w\\-\\_\u4e00-\u9fa5]{2,12}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    if (![emailTest evaluateWithObject:new])
    {
        [self.view toastMessage:@"密码长度要求在6-16位,且不能包含特殊字符" duration:1.f];
        return;
    }

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    __weak typeof(self) weakSelf = self;

    [PPNetworkService changePasswordWithNewPassword:new oldPassword:old callback:^(id data, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf == nil)
        {
            return;
        }

        [hud hide:YES];

        if(error == nil) {

            [strongSelf.navigationController.view toastMessage:@"修改成功" duration:2 completion:^{
                [strongSelf.navigationController popViewControllerAnimated:YES];
            }];

        } else {
            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
        }
    }];
}

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return 15;
//}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
    footerView.backgroundColor = [UIColor clearColor];
    UILabel *forgetPasswordLabel = [[UILabel alloc] initWithFrame:CGRectMake(footerView.width - 80, 0, 80, 40)];
    forgetPasswordLabel.text = @"忘记密码";
    forgetPasswordLabel.textAlignment = NSTextAlignmentCenter;
    forgetPasswordLabel.font = [UIFont systemFontOfSize:12];
    forgetPasswordLabel.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
    forgetPasswordLabel.backgroundColor = [UIColor clearColor];
    [footerView addSubview:forgetPasswordLabel];
    __weak typeof(self)weakSelf = self;
    [forgetPasswordLabel setActionBlock:^(UIControl *control) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
        PPRetrieveViewController *vc = [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([PPRetrieveViewController class])];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    } forEvent:UIControlEventTouchUpInside];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 40.f;
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([string isEqualToString:@"\n"]) {
        if(textField == _currentPasswordField) {
            [_nextPasswordField becomeFirstResponder];
        } else {
            [textField resignFirstResponder];
        }

        return NO;
    }

    return YES;
}

- (void)textFieldDidChanged
{
    NSString *old = _currentPasswordField.text;
    NSString *new = _nextPasswordField.text;
    if ([new length] == 0 || [old length] == 0)
    {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }
    else
    {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
}

@end
